package background
{
	import grid.Grid;

	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLRequest;

	/**
	 * @author robt
	 */
	public class Background extends Sprite
	{
		private var _loader : Loader;
		private var _grid : Grid;

		public function Background(grid : Grid)
		{
			_grid = grid;
		}

		public function loadImage(fileName : String) : void
		{
			reset();

			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
			_loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);

			var file:File = File.documentsDirectory.resolvePath("../Desktop/" + fileName); 
			var fileRequest : URLRequest = new URLRequest(file.url);
			
			_loader.load(fileRequest);
		}

		private function onIOError(event : IOErrorEvent) : void
		{
			trace("Rob>>> onIOError");
		}

		private function onSecurityError(event : SecurityErrorEvent) : void
		{
			trace("Rob>>> onSecurityError");
		}

		public function onLoadComplete(event : Event) : void
		{
			addChild(_loader);
 			_grid.onImageLoaded();
		}

		public function reset() : void
		{
			if (_loader)
			{
				if (contains(_loader))
				{
					removeChild(_loader);
				}

				_loader.unloadAndStop();
			}
		}
	}
}
